<template>
  <div class="edit-password">
    <el-dialog
      :title="updateParams.type == 'edit' ? '修改用户' : '注册用户'"
      center
      :visible.sync="dialogFormVisible"
      @close="resetForm('ruleForm')"
      top="5vh"
      width="500px"
    >
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        size="small"
        label-width="80px"
        class="demo-ruleForm"
        style="width: 400px; margin: 0 auto;"
      >
        <el-form-item label="ID" prop="user_id" ref="user_id">
          <el-input
            v-model.number="ruleForm.user_id"
            :disabled="updateParams.type === 'edit'"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="user_name">
          <el-input v-model="ruleForm.user_name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="user_sex">
          <el-radio-group v-model="ruleForm.user_sex">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="user_age">
          <el-input v-model="ruleForm.user_age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="user_phone">
          <el-input v-model="ruleForm.user_phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="系别" prop="dept_id">
          <el-select v-model="ruleForm.dept_id" placeholder="请选择">
            <el-option
              v-for="item in deptList"
              :key="item.dept_id"
              :label="item.dept_name"
              :value="item.dept_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select
            v-model="ruleForm.role"
            placeholder="请选择"
            :disabled="updateParams.type === 'edit'"
          >
            <el-option label="学生" value="student"></el-option>
            <el-option label="教师" value="teacher"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { register, getUserDetail, editUser } from '@/api/user'
import { deptList } from '@/api/dept'
export default {
  name: 'updateUser-pop',
  data() {
    const validateMobile = (rule, value, callback) => {
      const reg = /^1[3456789]\d{9}$/
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的手机号码'))
      }
    }
    const validateUserId = (rule, value, callback) => {
      if (value != '' && String(value).length > 5 && String(value).length < 12) {
        callback()
      } else {
        callback(new Error('请输入6~11个数字'))
      }
    }
    return {
      dialogFormVisible: false,
      ruleForm: {
        user_id: '',
        user_name: '',
        user_sex: 0,
        user_age: '',
        user_phone: '',
        dept_id: null,
        role: 'student'
      },
      rules: {
        user_id: [
          {
            validator: validateUserId,
            trigger: 'blur'
          }
        ],
        user_name: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }
        ],
        user_phone: [
          {
            validator: validateMobile,
            trigger: 'blur'
          }
        ],
        dept_id: [
          {
            required: true,
            message: '请选择系别',
            trigger: 'blur'
          }
        ]
      },
      deptList: [],
      updateParams: {},
    }
  },

  methods: {
    // 1.打开弹窗
    openMask(record) {
      this.updateParams = record
      if (record.type === 'edit') {
        this.userDetail(record.user_id)
      }
      this.getDeptList()
      this.dialogFormVisible = true
    },

    // 2.根据用户id获取用户详情
    userDetail(user_id) {
      getUserDetail({ user_id })
        .then(res => {
          if (res.result) {
            res.data.role = res.data.role[0]
            res.data.user_sex = Number(res.data.user_sex);
            this.ruleForm = { ...res.data }
            console.log(this.ruleForm, "rule form");
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },

    // 3.获取系别列表
    getDeptList() {
      deptList().then(res => {
        if (res.result) {
          this.deptList = res.data
        }
      })
    },

    // 4.注册/修改用户
    submitForm(formName) {
      if (this.updateParams.type == 'edit') {
        this.$refs['user_id'].clearValidate();
      }
      let api = this.updateParams.type === 'edit' ? editUser : register
      this.$refs[formName].validate(valid => {
        if (valid) {
          api(this.ruleForm)
            .then(res => {
              if (res.result) {
                this.resetForm('ruleForm')
                this.$message.success(res.message)
                this.$emit('ok')
              } else {
                this.$message.error(res.message)
              }
            })
            .catch(err => {
              this.$message.error(err.message)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.dialogFormVisible = false
    }
  }
}
</script>

<style lang="stylus" scoped>
.el-select {
  width 320px
}
</style>
